package com.budwk.app.sqfw.component;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwSummaryForAdminService;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 街道社区公共类
 */

@IocBean
@Slf4j
public class CommunityStreetComponent {

    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;
    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    /**
     * 删除数据
     * @param sqfwFormSummaryId
     */
    public void deleteFormSummary(String sqfwFormSummaryId) {
        Sqfw_formSummary sqfwFormSummary = sqfwSummaryForAdminService.fetch(sqfwFormSummaryId);
        if (sqfwFormSummary == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        sqfwCompleteflowService.deleteAndUpdateWO(sqfwFormSummary.getSqfwFlowId());
    }

    /**
     * 按照条件导出PDF
     * @param cnd 查询条件
     * @return
     */
    public String generateServiceRecordPdfCollZipForBM(Criteria cnd) {
        // 查询数据
        List<Sqfw_formSummary> list = sqfwSummaryForAdminService.query(cnd);
        if (list.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        List<SqfwSummaryPdfExcelCollForAdminDTO> results = Lists.newArrayList();
        list.forEach(e -> {
            if (StringUtils.isNotEmpty(e.getSqfwFlowId())) {
                SqfwSummaryPdfExcelCollForAdminDTO newCond = new SqfwSummaryPdfExcelCollForAdminDTO();
                newCond.setServiceType(e.getType()).setSumId(e.getId());
                results.add(newCond);
            }
        });
        // 2 导出数据
        String pdfUrl = sqfwSummaryForAdminService.generateServiceRecordPdfColl(results);
        log.info("generateServiceRecordPdfCollZipForBM generateServiceRecordPdfColl res: {}", pdfUrl);
        return pdfUrl;
    }

    /**
     * 查询导出：按照条件导出excel, 根据服务记录id和汇总Id数组生成Excel合集
     * @param bean 查询参数
     * @param cnd 条件
     * @return url
     */
    public String generateServiceRecordExcelCollZipForBM(Sqfw_formSummaryForAdminVO bean, Criteria cnd) {
        // 查询数据
        List<Sqfw_formSummary> list = sqfwSummaryForAdminService.query(cnd);
        if (list.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        List<String> sumIdList = list.stream().map(Sqfw_formSummary::getId).collect(Collectors.toList());
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateServiceSummaryExcelCollZipForBM(bean.getType(), bean.getCounty(), sumIdList, userId, bean.getFileIndexList(), "");
        log.info("generateServiceRecordExcelCollZipForBM res: {}", excelUrl);
        return excelUrl;
    }

    /**
     * 处理提交查询时间
     * @param forAdminVo 请求参数
     */
    public static void handleQueryTime(Sqfw_formSummaryForAdminVO forAdminVo, SqlExpressionGroup criSql) {
        forAdminVo.setFillStartDate(handleStartQueryTime(forAdminVo.getQueryStartTime()));
        forAdminVo.setFillEndDate(handleEndQueryTime(forAdminVo.getQueryEndTime()));
        criSql.andBetween(Sqfw_formSummary::getFillDate, forAdminVo.getFillStartDate(), forAdminVo.getFillEndDate());
    }

    // 会议时间处理
    public static void handleFillQueryTime(Sqfw_formSummaryForAdminVO forAdminVo, SqlExpressionGroup expressionSql) {
        // 是否需要查询
        boolean isQuery = forAdminVo.getFillStartDate() != null || forAdminVo.getFillEndDate() != null;
        forAdminVo.setFillStartDate(handleStartQueryTime(forAdminVo.getFillStartDate()));
        forAdminVo.setFillEndDate(handleEndQueryTime(forAdminVo.getFillEndDate()));
        if (isQuery) {
            expressionSql.andBetween(Sqfw_formSummary::getFillDate, forAdminVo.getFillStartDate(), forAdminVo.getFillEndDate());
        }
    }

    // 开始时间处理
    public static LocalDateTime handleStartQueryTime(LocalDateTime startQueryTime) {
        if (startQueryTime != null) {
            String startTime = LocalDateTimeUtil.format(startQueryTime, DatePattern.NORM_DATE_PATTERN) + " 00:00:00";
            return DateUtil.parseLocalDateTime(startTime);
        }
        return DateUtil.parseLocalDateTime("1970-01-01 00:00:00");
    }

    // 结束时间处理
    public static LocalDateTime handleEndQueryTime(LocalDateTime endQueryTime) {
        if (endQueryTime != null) {
            String endTime = LocalDateTimeUtil.format(endQueryTime, DatePattern.NORM_DATE_PATTERN) + " 23:59:59";
            return DateUtil.parseLocalDateTime(endTime);
        }
        return LocalDateTime.now();
    }
}
